import React, { useState, useEffect, useRef } from "react";
import { Link } from "react-router-dom";
import { useTranslation } from 'react-i18next';
import { AiOutlineWechat, AiOutlineQq, AiOutlineEye, AiOutlineEyeInvisible } from 'react-icons/ai';
import "./zhuce.css";
import axios from "axios";
import LoginLanguageSelector from '../../components/LoginLanguageSelector';

export default function Zhuce() {
    const { t } = useTranslation();
    // 注册方式: 'phone' 或 'email'
    const [registerType, setRegisterType] = useState("phone");
    
    // 表单数据
    const [formData, setFormData] = useState({
        
        username: "",
        phone: "",
        email: "",
        shenfen: "学生", // 默认为学生
        password: "",
        confirmPassword: "",
        verificationCode: "",
    });

    // 错误信息
    const [errors, setErrors] = useState({});
    
    // 密码可见性
    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);
    
    // 倒计时
    const [countdown, setCountdown] = useState(0);
    const timerRef = useRef(null);

    // 密码强度
    const [passwordStrength, setPasswordStrength] = useState({
        score: 0,
        hasLength: false,
        hasUpperCase: false,
        hasLowerCase: false,
        hasNumber: false,
        hasSymbol: false,
        noSpace: true,
        noRepeat: true,
        noConsecutive: true,
        noUsername: true,
    });

    // 处理注册类型切换
    const handleRegisterTypeChange = (type) => {
        setRegisterType(type);
        // 清空相应的表单字段
        setFormData({
            ...formData,
            phone: type === "phone" ? formData.phone : "",
            email: type === "email" ? formData.email : "",
            verificationCode: "",
        });
        // 清空相应的错误信息
        setErrors({
            ...errors,
            phone: "",
            email: "",
            verificationCode: "",
        });
    };

    // 处理表单输入变化
    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value,
        });

        // 清除错误信息
        if (errors[name]) {
            setErrors({
                ...errors,
                [name]: "",
            });
        }

        // 如果是密码，检查密码强度
        if (name === "password") {
            checkPasswordStrength(value);
        }
    };

    // 检查密码强度
    const checkPasswordStrength = (password) => {
        const hasLength = password.length >= 8 && password.length <= 16;
        const hasUpperCase = /[A-Z]/.test(password);
        const hasLowerCase = /[a-z]/.test(password);
        const hasNumber = /[0-9]/.test(password);
        const hasSymbol = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password);
        const noSpace = !/\s/.test(password);
        const noRepeat = !/(.)\1\1/.test(password); // 不能有连续重复3个及以上的字符
        const noConsecutive = !/(?:abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789|890)/i.test(password); // 不能有连续3个及以上的字符或数字
        
        // 检查密码是否包含用户名或邮箱前缀
        const containsUsername = formData.username && password.toLowerCase().includes(formData.username.toLowerCase());
        const containsEmailPrefix = formData.email && password.toLowerCase().includes(formData.email.split('@')[0].toLowerCase());
        const noUsername = !containsUsername && !containsEmailPrefix;

        let score = 0;
        if (hasLength) score++;
        if (hasUpperCase) score++;
        if (hasLowerCase) score++;
        if (hasNumber) score++;
        if (hasSymbol) score++;
        if (noSpace) score++;
        if (noRepeat) score++;
        if (noConsecutive) score++;
        if (noUsername) score++;

        setPasswordStrength({
            score,
            hasLength,
            hasUpperCase,
            hasLowerCase,
            hasNumber,
            hasSymbol,
            noSpace,
            noRepeat,
            noConsecutive,
            noUsername,
        });
    };

    // 获取密码强度描述
    const getPasswordStrengthText = () => {
        const { score } = passwordStrength;
        if (score <= 1) return t("password_strength_weak");
        if (score <= 3) return t("password_strength_medium");
        return t("password_strength_strong");
    };

    // 获取密码强度颜色
    const getPasswordStrengthColor = () => {
        const { score } = passwordStrength;
        if (score <= 1) return "#ff4d4f";
        if (score <= 3) return "#faad14";
        return "#52c41a";
    };

    // 发送验证码
    const sendVerificationCode = async () => {
        // 验证手机号或邮箱
        let isValid = true;
        const newErrors = { ...errors };

        if (registerType === "phone") {
            if (!formData.phone) {
                newErrors.phone = t("phone_required");
                isValid = false;
            } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
                newErrors.phone = t("phone_invalid");
                isValid = false;
            }
        } else {
            if (!formData.email) {
                newErrors.email = t("email_required");
                isValid = false;
            } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
                newErrors.email = t("email_invalid");
                isValid = false;
            }
        }

        if (!isValid) {
            setErrors(newErrors);
            return;
        }

        try {
            // 开始倒计时
            setCountdown(60);
            
            // 发送验证码API请求
            const response = await axios.post('http://localhost:3001/lxt/send-verification-code', {
                type: registerType, // 'phone' 或 'email'
                target: registerType === "phone" ? formData.phone : formData.email,
                purpose: 'register' // 用途：注册、登录、找回密码等
            });

            if (response.data.code === 200) {
                console.log(`验证码已发送到${registerType === "phone" ? "手机" + formData.phone : "邮箱" + formData.email}`);
                alert(`${t("verification_code_sent")}${registerType === "phone" ? formData.phone : formData.email}`);
            } else {
                throw new Error(response.data.msg || t("send_verification_code_failed"));
            }
        } catch (error) {
            // 发送失败，停止倒计时
            setCountdown(0);
            
            console.error('发送验证码失败:', error);
            
            if (error.response && error.response.data && error.response.data.message) {
                alert(`${t("send_verification_code_failed")}: ${error.response.data.message}`);
            } else {
                alert(`${t("send_verification_code_failed")}`);
            }
        }
    };

    // 处理第三方登录
    const handleThirdPartyLogin = async (platform) => {
        try {
            console.log(`使用${platform}扫码授权登录`);
            
            // 转换平台名称为API参数
            const typeMap = {
                '微信': 'wechat',
                'QQ': 'qq',
                'wechat': 'wechat',
                'qq': 'qq'
            }
            const type = typeMap[platform] || platform.toLowerCase();
            
            // 调用水滴聚合登录API获取登录链接
            const response = await axios.get(`http://localhost:3001/lxt/shuidi-login?type=${type}`);
            
            if (response.data && response.data.code === 200 && response.data.loginUrl) {
                console.log(`✅ 获取${platform}登录链接成功`);
                
                // 在原窗口跳转到登录链接
                window.location.href = response.data.loginUrl;
                
            } else {
                throw new Error(response.data?.msg || t("get_login_url_failed"));
            }
            
        } catch (err) {
            console.error(`${platform}登录出错:`, err);
            alert(`${t("third_party_login_failed")}: ${err.message || t("please_try_again")}`);
        }
    };

    // 表单提交
    const handleSubmit = async (e) => {
        e.preventDefault();
        
        // 表单验证
        const newErrors = {};
        let isValid = true;

        // 验证昵称
        if (!formData.username.trim()) {
            newErrors.username = t("username_required");
            isValid = false;
        }

        // 验证手机号或邮箱
        if (registerType === "phone") {
            if (!formData.phone) {
                newErrors.phone = t("phone_required");
                isValid = false;
            } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
                newErrors.phone = t("phone_invalid");
                isValid = false;
            }
        } else {
            if (!formData.email) {
                newErrors.email = t("email_required");
                isValid = false;
            } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
                newErrors.email = t("email_invalid");
                isValid = false;
            }
        }

        // 验证验证码
        if (!formData.verificationCode) {
            newErrors.verificationCode = t("verification_code_required");
            isValid = false;
        } else if (formData.verificationCode.length !== 6) {
            newErrors.verificationCode = t("verification_code_length");
            isValid = false;
        }

        // 验证密码
        if (!formData.password) {
            newErrors.password = t("password_required");
            isValid = false;
        } else {
            // 密码复杂度检查
            const { hasLength, hasUpperCase, hasLowerCase, hasNumber, hasSymbol, noSpace, noRepeat, noConsecutive, noUsername } = passwordStrength;
            const conditionsMet = [hasUpperCase, hasLowerCase, hasNumber, hasSymbol].filter(Boolean).length;
            
            if (!hasLength) {
                newErrors.password = t("password_length_8_16");
                isValid = false;
            } else if (conditionsMet < 3) {
                newErrors.password = t("password_at_least_three_types");
                isValid = false;
            } else if (!noSpace) {
                newErrors.password = t("password_no_space");
                isValid = false;
            } else if (!noRepeat) {
                newErrors.password = t("password_no_repeat_three_chars");
                isValid = false;
            } else if (!noConsecutive) {
                newErrors.password = t("password_no_consecutive_chars_or_numbers");
                isValid = false;
            } else if (!noUsername) {
                newErrors.password = t("password_no_username");
                isValid = false;
            }
        }

        // 验证确认密码
        if (!formData.confirmPassword) {
            newErrors.confirmPassword = t("confirm_password_required");
            isValid = false;
        } else if (formData.password !== formData.confirmPassword) {
            newErrors.confirmPassword = t("passwords_do_not_match");
            isValid = false;
        }

        if (!isValid) {
            setErrors(newErrors);
            return;
        }

        // 表单验证通过，提交注册信息
        try {
            const registerData = {
                username: formData.username,
                shenfen: formData.shenfen,
                password: formData.password,
                verificationCode: formData.verificationCode,
                type: registerType
            };
            
            // 根据注册类型添加相应的字段
            if (registerType === "phone") {
                registerData.phone = formData.phone;
            } else if (registerType === "email") {
                registerData.email = formData.email;
            }
            
            console.log('发送注册数据:', registerData);
            
            const response = await axios.post("http://localhost:3001/lxt/register", registerData);

            if (response.data.code === 200) {
                alert(`${t("registration_successful")}！${t("redirecting_to_login")}`);
                // 注册成功后跳转到登录页
                window.location.href = '/login';
            } else {
                setErrors({ 
                    ...errors, 
                    verificationCode: response.data.msg || t("registration_failed") 
                });
            }
        } catch (error) {
            console.error('注册失败:', error);
            
            if (error.response && error.response.data) {
                if (error.response.data.field) {
                    // 特定字段错误
                    setErrors({
                        ...errors,
                        [error.response.data.field]: error.response.data.msg
                    });
                } else {
                    // 通用错误
                    alert(`${t("registration_failed")}: ${error.response.data.msg}`);
                }
            } else {
                alert(`${t("registration_failed")}，${t("please_try_again")}`);
            }
        }
    };

    // 倒计时逻辑
    useEffect(() => {
        if (countdown > 0) {
            timerRef.current = setTimeout(() => {
                setCountdown(countdown - 1);
            }, 1000);
        }

        return () => {
            if (timerRef.current) {
                clearTimeout(timerRef.current);
            }
        };
    }, [countdown]);

    return (
                  <div className="register-container">
              {/* 语言选择器 - 固定在右上角 */}
              <LoginLanguageSelector />
            
            <div className="register-form-wrapper">
                <div className="register-form">
                    <div className="register-header">
                        <h2>{t("user_registration")}</h2>
                        <Link to="/login" className="login-link">{t("already_have_an_account")}？{t("log_in_now")}</Link>
                    </div>

                    <div className="register-type-selector">
                        <div
                            className={`register-type-option ${registerType === "phone" ? "active" : ""}`}
                            onClick={() => handleRegisterTypeChange("phone")}
                        >
                            {t("phone_registration")}
                        </div>
                        <div
                            className={`register-type-option ${registerType === "email" ? "active" : ""}`}
                            onClick={() => handleRegisterTypeChange("email")}
                        >
                            {t("email_registration")}
                        </div>
                    </div>

                    <form onSubmit={handleSubmit}>
                        <div className="form-group">
                            <label htmlFor="username">{t("username")}</label>
                            <input
                                id="username"
                                type="text"
                                name="username"
                                value={formData.username}
                                onChange={handleInputChange}
                                placeholder={t("please_enter_username")}
                            />
                            {errors.username && <span className="error-message">{errors.username}</span>}
                        </div>

                        <div className="form-group">
                            <label htmlFor="shenfen">{t("identity_information")}</label>
                            <select
                                id="shenfen"
                                name="shenfen"
                                value={formData.shenfen}
                                onChange={handleInputChange}
                            >
                                <option value="学生">{t("student")}</option>
                                <option value="教师">{t("teacher")}</option>
                            </select>
                        </div>

                        {registerType === "phone" ? (
                            <div className="form-group">
                                <label htmlFor="phone">{t("phone_number")}</label>
                                <input
                                    id="phone"
                                    type="tel"
                                    name="phone"
                                    value={formData.phone}
                                    onChange={handleInputChange}
                                    placeholder={t("please_enter_phone_number")}
                                />
                                {errors.phone && <span className="error-message">{errors.phone}</span>}
                            </div>
                        ) : (
                            <div className="form-group">
                                <label htmlFor="email">{t("email")}</label>
                                <input
                                    id="email"
                                    type="email"
                                    name="email"
                                    value={formData.email}
                                    onChange={handleInputChange}
                                    placeholder={t("please_enter_email")}
                                />
                                {errors.email && <span className="error-message">{errors.email}</span>}
                            </div>
                        )}

                        <div className="form-group verification-group">
                            <label htmlFor="verificationCode">{t("verification_code")}</label>
                            <div className="verification-input-group">
                                <input
                                    id="verificationCode"
                                    type="text"
                                    name="verificationCode"
                                    value={formData.verificationCode}
                                    onChange={handleInputChange}
                                    placeholder={t("please_enter_verification_code")}
                                    maxLength={6}
                                />
                                <button
                                    type="button"
                                    className="verification-code-btn"
                                    onClick={sendVerificationCode}
                                    disabled={countdown > 0}
                                >
                                    {countdown > 0 ? `${countdown}${t("seconds_later_resend")}` : t("get_verification_code")}
                                </button>
                            </div>
                            {errors.verificationCode && (
                                <span className="error-message">{errors.verificationCode}</span>
                            )}
                        </div>

                        <div className="form-group password-group">
                            <label htmlFor="password">{t("password")}</label>
                            <div className="password-input-wrapper">
                                <input
                                    id="password"
                                    type={showPassword ? "text" : "password"}
                                    name="password"
                                    value={formData.password}
                                    onChange={handleInputChange}
                                    placeholder={t("please_set_8_16_password")}
                                />
                                <span
                                    className="toggle-password"
                                    onClick={() => setShowPassword(!showPassword)}
                                >
                                    {showPassword ? <AiOutlineEye /> : <AiOutlineEyeInvisible />}
                                </span>
                            </div>
                            {formData.password && (
                                <div className="password-strength">
                                    <div className="strength-label">{t("password_strength")}：</div>
                                    <div 
                                        className="strength-value" 
                                        style={{ color: getPasswordStrengthColor() }}
                                    >
                                        {getPasswordStrengthText()}
                                    </div>
                                    <div className="strength-meter">
                                        <div 
                                            className="strength-meter-fill" 
                                            style={{ 
                                                width: `${(passwordStrength.score / 5) * 100}%`,
                                                backgroundColor: getPasswordStrengthColor()
                                            }}
                                        ></div>
                                    </div>
                                </div>
                            )}
                            {errors.password && <span className="error-message">{errors.password}</span>}
                        </div>

                        <div className="password-rules">
                            <div className={`rule ${passwordStrength.hasLength ? 'valid' : ''}`}>
                                ✓ {t("password_length_8_16")}
                            </div>
                            <div className={`rule ${[passwordStrength.hasUpperCase, passwordStrength.hasLowerCase, passwordStrength.hasNumber, passwordStrength.hasSymbol].filter(Boolean).length >= 3 ? 'valid' : ''}`}>
                                ✓ {t("password_at_least_three_types")}
                            </div>
                            <div className={`rule ${passwordStrength.noSpace ? 'valid' : ''}`}>
                                ✓ {t("password_no_space")}
                            </div>
                            <div className={`rule ${passwordStrength.noRepeat && passwordStrength.noConsecutive ? 'valid' : ''}`}>
                                ✓ {t("password_no_repeat_three_chars")}
                            </div>
                            <div className={`rule ${passwordStrength.noUsername ? 'valid' : ''}`}>
                                ✓ {t("password_no_username")}
                            </div>
                        </div>

                        <div className="form-group password-group">
                            <label htmlFor="confirmPassword">{t("confirm_password")}</label>
                            <div className="password-input-wrapper">
                                <input
                                    id="confirmPassword"
                                    type={showConfirmPassword ? "text" : "password"}
                                    name="confirmPassword"
                                    value={formData.confirmPassword}
                                    onChange={handleInputChange}
                                    placeholder={t("please_enter_password_again")}
                                />
                                <span
                                    className="toggle-password"
                                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                >
                                    {showConfirmPassword ? <AiOutlineEye /> : <AiOutlineEyeInvisible />}
                                </span>
                            </div>
                            {errors.confirmPassword && (
                                <span className="error-message">{errors.confirmPassword}</span>
                            )}
                        </div>

                        <button type="submit" className="register-btn">{t("register")}</button>
                    </form>

                    <div className="third-party-register">
                        <div className="divider">
                            <span>{t("other_registration_methods")}</span>
                        </div>
                        <div className="third-party-icons">
                            <div
                                className="third-party-icon wechat"
                                onClick={() => handleThirdPartyLogin("微信")}
                                title={t("wechat_scan_to_register")}
                            >
                                <AiOutlineWechat size={24} />
                            </div>
                            <div
                                className="third-party-icon qq"
                                onClick={() => handleThirdPartyLogin("QQ")}
                                title={t("qq_scan_to_register")}
                            >
                                <AiOutlineQq size={24} />
                            </div>
                        </div>
                    </div>

                    <div className="agreement">
                        {t("register_means_you_agree")} <Link to="/terms">{t("terms_of_service")}</Link> {t("and")} <Link to="/privacy">{t("privacy_policy")}</Link>
                    </div>
                </div>
            </div>
        </div>
    );
}